from imp import reload

from bs4 import BeautifulSoup
import requests
import time
import sys

# 定义url
# city = input("请输入城市：")
url = "http://news.baidu.com/ns?cl=2&rn=20&tn=news&word=%E9%98%9C%E9%98%B3"



def sleep_time(hour, minute, sec):
    return hour*3600 + minute * 60 + sec

while 1 == 1:
    r = requests.get(url)
    html = r.text
    soup = BeautifulSoup(html, 'html.parser')
    # 取出结果div
    div_items = soup.find_all('div', class_='result')

    for div in div_items:
        # 取出title , 链接
        a_title = div.find('h3', class_='c-title').find('a').get_text()
        a_href = div.find('h3', class_='c-title').find('a').get('href')
        # 取出简介
        a_summary = div.find('div', class_='c-summary').get_text()
        # 获取当前时间
        now = time.strftime('%m-%d-%H-%M-%S', time.localtime(time.time()))
        path = "/home/files/lx/news/"
        macPath ="/Users/lixiang/files/"
        area = "fuyang&"
        with open(path + area + now + '.txt', 'a', encoding='utf-8') as file:
            file.write("title: " + a_title + "\n")
            file.write("href: " + a_href + "\n")
            file.write("summary: " + a_summary + "\n\n")

    time.sleep(sleep_time(5, 0, 0))